package cn.pconline.autoclub.service;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Activity;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.CityDyna;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubDyna;
import cn.pconline.autoclub.entity.DynaImage;
import cn.pconline.autoclub.entity.DynaInfo;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.entity.Vote;
import cn.pconline.autoclub.util.BrandIdUrlMap;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.officialclub.entity.OActivity;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.service.OActivityService;
import cn.pconline.officialclub.service.OClubService;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

/**
 * 动态相关的查询
 *
 * @email chensy0203@163.com
 * @author chensy
 */
public class EffectiveDynaService extends DynaService {

    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private SystemConfig systemConfig;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private AlbumService albumService;
    @Autowired
    private ActivityService activityService;
    @Autowired
    private VoteService voteService;
	@Autowired
	private OActivityService oActivityService;
    @Autowired
    private OClubService oClubService;
    
    private static final Logger log = LoggerFactory.getLogger(EffectiveDynaService.class);

    /**
     * 获取某一动态（包括图片）
     *
     * @param createDate
     * @param id
     * @return
     */
    public DynaInfo findDynaById(long id, Date createDate) {
        List<DynaInfo> list = findDynaByIds(createDate, id);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 批量获取动态（包括图片）
     *
     * @param createDate
     * @param ids
     * @return
     */
    public List<DynaInfo> findDynaByIds(final Date createDate, Object... ids) {
        List<DynaInfo> list = new ArrayList<DynaInfo>();
        for (Object id : ids) {
            String key = DYNA_MC_KEY + id;
            Object obj = mcc.get(key);
            if (obj != null) {
                DynaInfo dynaInfo = GeliDao.string2Object(DynaInfo.class, (String) obj);
                list.add(dynaInfo);
                continue;
            }
            SqlBuilder sql = new SqlBuilder();
            sql.appendSql("select * from ").appendSql(geliOrm.getTableName(DynaInfo.class, createDate.getTime())).appendSql(" info left join ");
            sql.appendSql(geliOrm.getTableName(DynaImage.class, (Long) id)).appendSql(" img ");
            sql.appendSql(" on info.dyna_info_id = img.dyna_info_id where info.dyna_info_id  = ").appendValue(id);
            sql.appendSql(" limit ").appendValue(MAX_PICTURE_NUM);
            DynaInfo info = jdbcTemplate.query(sql.getSql(), sql.getValues(), new ResultSetExtractor<DynaInfo>() {
                @Override
                public DynaInfo extractData(ResultSet rs) throws SQLException, DataAccessException {
                    DynaInfo info = null;
                    while (rs.next()) {
                        if (info == null) {
                            info = new DynaInfo();
                            info.setCensored(rs.getInt("censored"));
                            info.setCityId(rs.getLong("city_id"));
                            info.setClubId(rs.getLong("club_id"));
                            info.setContent(rs.getString("content"));
                            info.setCreateAt(rs.getTimestamp("create_at"));
                            info.setCreateBy(rs.getLong("create_by"));
                            info.setCreateDate(rs.getTimestamp("create_date"));
                            info.setCreateName(rs.getString("create_name"));
                            info.setDynaInfoId(rs.getLong("dyna_info_id"));
                            info.setForumId(rs.getLong("forum_id"));
                            info.setForumName(rs.getString("forum_name"));
                            info.setImages(new ArrayList<DynaImage>());
                            info.setIsOfficialClubDyna(rs.getInt("is_official_club_dyna"));
                            info.setIsPic(rs.getInt("is_pic"));
                            info.setLastPostAt(rs.getTimestamp("last_post_at"));
                            info.setLastPostBy(rs.getLong("last_post_by"));
                            info.setLastPostName(rs.getString("last_post_name"));
                            info.setPetrol(rs.getInt("petrol"));
                            info.setPick(rs.getInt("pick"));
                            info.setPostCount(rs.getInt("post_count"));
                            info.setPraiseCount(rs.getLong("praise_count"));
                            info.setProvinceId(rs.getLong("province_id"));
                            info.setRecommend(rs.getInt("recommend"));
                            info.setStatus(rs.getInt("status"));
                            info.setSubjectIds(rs.getString("subject_ids"));
                            info.setTargetId(rs.getLong("target_id"));
                            info.setTitle(rs.getString("title"));
                            info.setTopicId(rs.getLong("topic_id"));
                            info.setType(rs.getInt("type"));
                            info.setUpdateAt(rs.getTimestamp("update_at"));
                            info.setUpdateBy(rs.getLong("update_by"));
                            info.setFromType(rs.getInt("from_type"));
                        }
                        if (info.getIsPic() == DynaInfo.PIC_NOT) {
                            break;
                        }
                        DynaImage img = new DynaImage();
                        img.setDynaInfoId(rs.getLong("dyna_info_id"));
                        img.setHeight(rs.getInt("height"));
                        img.setImageId(rs.getLong("image_id"));
                        img.setSeq(rs.getInt("seq"));
                        img.setUrl(rs.getString("url"));
                        img.setWidth(rs.getInt("width"));
                        info.getImages().add(img);
                    }
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(createDate);
                    if (info != null && info.isTopic() && cal.get(Calendar.YEAR) < 2013) {//2013前的帖子没有120*80，500x500
                        log.warn("topic dyna[{}] create at {} before the year 2013 not 120x80,500x500 images", info.getDynaInfoId(), createDate);
                        info.setImages(Collections.EMPTY_LIST);
                    }
                    return info;
                }
            });
            if (info != null) {
                list.add(info);
                mcc.set(key, JSONObject.toJSONString(info));
            }
        }
        if (ids.length > list.size()) {
            log.error("可能有脏数据！[{},{}]部分动态信息不存在", StringUtil.toString(ids), createDate);
        }
        return list;
    }

    /**
     * 通用方法，根据sql查动态列表（同城动态、车友会动态、和用户动态等等）
     *
     * @param sql 必须包含这两个字段 select dyna_info_id,create_date
     * @param orderSql
     * @param selectSql 必须包含这两个字段 select dyna_info_id,create_date
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<DynaInfo> getDynaListBySql(SqlBuilder sql, String orderSql, String selectSql, int pageNo, int pageSize) {
        int total = jdbcTemplate.queryForInt(sql.getSql().replace(selectSql, "select count(1) "), sql.getValues());
        if (total == 0) {
            return null;
        }
        Pager<DynaInfo> pager = new Pager<DynaInfo>();
        pager.setPageNo(pageNo);
        pager.setPageSize(pageSize);
        pager.setTotal(total);
        if (total == 0 || pageNo > pager.getPageCount() || (pageNo - 1) * pageSize < 0) {
            return null;
        }
        if (orderSql != null) {
            sql.appendSql(orderSql);
        }
        sql.appendSql(" limit ").appendValue((pageNo - 1) * pageSize).appendSql(",").appendValue(pageSize);
        List<DynaInfo> list = jdbcTemplate.query(sql.getSql(), sql.getValues(), new ResultSetExtractor<List<DynaInfo>>() {
            @Override
            public List<DynaInfo> extractData(ResultSet rs) throws SQLException, DataAccessException {
                List<DynaInfo> dynaList = new ArrayList<DynaInfo>();
                while (rs.next()) {
                    long dynaInfoId = rs.getLong("dyna_info_id");
                    Date createDate = rs.getTimestamp("create_date");
                    DynaInfo info = new DynaInfo();
                    info.setDynaInfoId(dynaInfoId);
                    info.setCreateDate(createDate);
                    dynaList.add(info);
                }
                return dynaList;
            }
        });
        //对查询结果可以按时间分组，批量去查。大部分情况，查询的数据应该是在同一张表的，可以减少查询
        Map<Integer, List<Long>> map = new LinkedHashMap<Integer, List<Long>>();
        for (DynaInfo info : list) {
            int year = DateUtils.getYear(info.getCreateDate());
            List<Long> ids = map.get(year);
            if (ids == null) {
                ids = new ArrayList<Long>();
                map.put(year, ids);
            }
            ids.add(info.getDynaInfoId());
        }
        List<DynaInfo> dynaList = new ArrayList<DynaInfo>(list.size());
        for (Integer year : map.keySet()) {
            List<Long> ids = map.get(year);
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.YEAR, year);
            List<DynaInfo> li = findDynaByIds(cal.getTime(), ids.toArray());
            if (li == null || li.isEmpty()) {
                log.error("可能有脏数据！[{},{}]全部动态信息不存在", StringUtil.toString(ids.toArray()), cal.getTime());
                continue;
            } else {
                dynaList.addAll(li);
            }
        }
        if (dynaList.isEmpty()) {
            return null;
        }
        pager.setResultList(dynaList);
        return pager;
    }

    public Pager<DynaInfo> getDynaListByClubId(long clubId, int pageNo, int pageSize, Integer... type) {
        return getDynaListByClubId(clubId, null, null, pageNo, pageSize, type);
    }

    /**
     * 根据动态ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param clubId
     * @param pick
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    private Pager<DynaInfo> getDynaListByClubId(long clubId, Boolean isPick, Boolean isTop, int pageNo, int pageSize, Integer... type) {
        SqlBuilder sql = new SqlBuilder();
        String selectSql = "select dyna_info_id,create_date ";
        sql.appendSql(selectSql);
        sql.appendSql(" from ").appendSql(geliOrm.getTableName(ClubDyna.class, clubId));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and status !=").appendValue(DynaInfo.STATUS_DELETE);
        if (isPick != null) {
            sql.appendSql(" and pick = ").appendValue(isPick ? 1 : 0);
        }
        if (type != null && type.length > 0) {
            sql.appendSql(" and type in ").appendValues(type);
        }
        String orderSql;
        if (isTop != null) {
            if (isTop) {
                sql.appendSql(" and is_top = ").appendValue(ClubDyna.TOP_YES);
                orderSql = " order by top_date desc,create_date desc ";
            } else {
                sql.appendSql(" and is_top = ").appendValue(ClubDyna.TOP_NO);
                orderSql = (" order by create_date desc ");
            }
        } else {
            orderSql = (" order by create_date desc ");
        }
        return getDynaListBySql(sql, orderSql, selectSql, pageNo, pageSize);
    }

    /**
     * 根据车友会ID分页查询动态列表（不包括图片），按order排序
     *
     * @param clubId
     * @param pick
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getDynaListByClubIdOrder(long clubId, int pageNo, int pageSize, int order, Integer... type) {
        SqlBuilder sql = new SqlBuilder();
        String selectSql = "select dyna_info_id,create_date ";
        sql.appendSql(selectSql);
        sql.appendSql(" from ").appendSql(geliOrm.getTableName(ClubDyna.class, clubId));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and status !=").appendValue(DynaInfo.STATUS_DELETE);
        if (type != null && type.length > 0) {
            sql.appendSql(" and type in ").appendValues(type);
        }
        String orderSql;
        if (order == ORDER_POST_DATE) {
            orderSql = " order by last_post_at desc";
        } else {
            orderSql = " order by create_date desc";
        }
        return getDynaListBySql(sql, orderSql, selectSql, pageNo, pageSize);
    }

    /**
     * 根据动态ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getDynaListByClubId(long clubId, int pageNo, int pageSize) {
        return getDynaListByClubId(clubId, null, null, pageNo, pageSize);
    }

    /**
     * 根据车友会ID，动态类型（可多种），查询动态列表 （包括图片也会查出来）
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @param types
     * @return
     */
    public Pager<DynaInfo> getDynaListByClubIdTypes(long clubId, int pageNo, int pageSize, Integer... types) {
        return getDynaListByClubId(clubId, null, null, pageNo, pageSize, types);
    }

    /**
     * 根据动态ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getTopDynaListByClubId(long clubId, int num) {
        return getDynaListByClubId(clubId, null, true, 1, num);
    }

    /**
     * 根据动态ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getTopicDynaListByClubId(long clubId, int pageNo, int pageSize) {
        return getDynaListByClubId(clubId, null, false, pageNo, pageSize, DynaInfo.getTopicType());
    }

    /**
     * 重载 前面的查询方法，添加排序参数order
     *
     */
    public Pager<DynaInfo> getTopicDynaListByClubId(long clubId, int pageNo, int pageSize, int order) {
        return getDynaListByClubIdOrder(clubId, null, false, pageNo, pageSize, order, DynaInfo.getTopicType());
    }

    /**
     * 根据车友会ID分布查询留言列表
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<DynaInfo> getCommentDynaListByClubId(long clubId, int pageNo, int pageSize) {
        return getDynaListByClubId(clubId, null, null, pageNo, pageSize, DynaInfo.TYPE_COMMENT);
    }

    /**
     * 根据动态ID分页查询动态列表（包括图片也会查出来），按order排序
     *
     * @param clubId
     * @param pick
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    private Pager<DynaInfo> getDynaListByClubIdOrder(long clubId, Boolean isPick, Boolean isTop, int pageNo, int pageSize, int order, Integer... type) {
        SqlBuilder sql = new SqlBuilder();
        String selectSql = "select dyna_info_id,create_date ";
        sql.appendSql(selectSql);
        sql.appendSql(" from ").appendSql(geliOrm.getTableName(ClubDyna.class, clubId));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and status !=").appendValue(DynaInfo.STATUS_DELETE);
        if (isPick != null) {
            sql.appendSql(" and pick = ").appendValue(isPick ? 1 : 0);
        }
        if (type != null && type.length > 0) {
            sql.appendSql(" and type in ").appendValues(type);
        }
        String orderSql;
        if (isTop != null && isTop) {
            sql.appendSql(" and is_top = ").appendValue(ClubDyna.TOP_YES);
            if (order == ORDER_POST_DATE) {
                orderSql = " order by top_date,last_post_at desc";
            } else {
                orderSql = " order by top_date,create_date desc";
            }

        } else {
            sql.appendSql(" and is_top = ").appendValue(ClubDyna.TOP_NO);
            if (order == ORDER_POST_DATE) {
                orderSql = " order by last_post_at desc";
            } else {
                orderSql = " order by create_date desc";
            }
        }
        return getDynaListBySql(sql, orderSql, selectSql, pageNo, pageSize);
    }

    /**
     * 根据动态ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getPickTopicDynaListByClubId(long clubId, int pageNo, int pageSize, int order) {
        return getDynaListByClubIdOrder(clubId, true, null, pageNo, pageSize, order, DynaInfo.getTopicType());
    }

    /**
     * 根据省份和城市ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param provinceId
     * @param cityId
     * @param type
     * @param isPick
     * @param pageNo
     * @param pageSize
     * @return
     */
    private Pager<DynaInfo> getDynaListByCityId(long provinceId, long cityId, Integer type, Boolean isPick, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        String selectSql = "select dyna_info_id,create_date ";
        sql.appendSql(selectSql);
        sql.appendSql(" from ").appendSql(geliOrm.getTableName(CityDyna.class, cityId));
        sql.appendSql(" where province_id = ").appendValue(provinceId);
        sql.appendSql(" and city_id = ").appendValue(cityId);
        sql.appendSql(" and status !=").appendValue(CityDyna.STATUS_DELETE);
        if (isPick != null) {
            sql.appendSql(" and pick = ").appendValue(isPick ? 1 : 0);
        }
        if (type != null) {
            sql.appendSql(" and type = ").appendValue(type);
        }
        String orderSql = (" order by create_date desc ");
        return getDynaListBySql(sql, orderSql, selectSql, pageNo, pageSize);
    }

    /**
     * 根据省份和城市ID分页查询动态（留言动态）列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param userId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getCommentDynaListByCityId(long provinceId, long cityId, int pageNo, int pageSize) {
        return getDynaListByCityId(provinceId, cityId, DynaInfo.TYPE_COMMENT, null, pageNo, pageSize);
    }

    /**
     * 根据省份和城市ID分页查询动态（留言+帖子）列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param userId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getDynaListByCityId(long provinceId, long cityId, int pageNo, int pageSize) {
        return getDynaListByCityId(provinceId, cityId, null, null, pageNo, pageSize);
    }

    /**
     * 根据省份和城市ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序 可查询指定多种动态类型
     *
     * @param provinceId
     * @param cityId
     * @param type
     * @param isPick
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<DynaInfo> getDynaListByCityIdDynaType(long provinceId, long cityId, List<Integer> typeList, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        String selectSql = "select dyna_info_id,create_date ";
        sql.appendSql(selectSql);
        sql.appendSql(" from ").appendSql(geliOrm.getTableName(CityDyna.class, cityId));
        sql.appendSql(" where province_id = ").appendValue(provinceId);
        sql.appendSql(" and city_id = ").appendValue(cityId);
        sql.appendSql(" and status !=").appendValue(CityDyna.STATUS_DELETE);
        sql.appendSql(" and type in ").appendValues(typeList.toArray());
        String orderSql = (" order by create_date desc ");
        return getDynaListBySql(sql, orderSql, selectSql, pageNo, pageSize);
    }

    /**
     * 根据用户ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序
     *
     * @param userId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getDynaListByUserId(long userId, Boolean isPick, int pageNo, int pageSize, Integer... type) {

        SqlBuilder sql = new SqlBuilder();
        String selectSql = "select dyna_info_id,create_date ";
        sql.appendSql(selectSql);
        sql.appendSql(" from ac_user_dyna_").appendSql(userId % 10 + "");
        sql.appendSql(" where user_id = ").appendValue(userId);
        sql.appendSql(" and status !=").appendValue(DynaInfo.STATUS_DELETE);
        if (isPick != null) {
            sql.appendSql(" and pick = ").appendValue(isPick ? 1 : 0);
        }
        if (type != null && type.length > 0) {
            sql.appendSql(" and type in ").appendValues(type);
        }
        String orderSql = (" order by create_date desc ");
        return getDynaListBySql(sql, orderSql, selectSql, pageNo, pageSize);
    }

    /**
     * 根据用户ID分页查询动态列表（包括图片也会查出来），按最新的发布时间排序，所有动态
     *
     * @param userId
     * @param pageNo
     * @param pageSize
     * @return 无查询结果返回NULL
     */
    public Pager<DynaInfo> getDynaListByUserId(long userId, int pageNo, int pageSize) {
        return getDynaListByUserId(userId, null, pageNo, pageSize);
    }

    /**
     * 组装动态Json
     *
     * @param dynaInfo
     * @param xssEncode
     * @return
     */
    public JSONObject toJson4App(DynaInfo dynaInfo, int xssEncode) {
        //获取配置文件中的动态切图参数
        int imageQua = systemConfig.getImageQua();

        JSONObject json = new JSONObject();
        json.put("dynaInfoId", dynaInfo.getDynaInfoId());
        //回帖数
        json.put("postCount", dynaInfo.getPostCount());
        //动态发布时间
        json.put("pubTime", dynaInfo.getCreateDate());
        //帖子Title
        json.put("topicTitle", dynaInfo.getTitle() == null ? ""
                : dynaInfo.getTitle());
        //用户ID
        json.put("authorId", dynaInfo.getCreateBy());
        json.put("createBy", dynaInfo.getCreateBy());// TODO 等APP4.0上线后，可以删除上面那个
        //版块ID
        json.put("forumId", dynaInfo.getForumId());
        json.put("forumName", dynaInfo.getForumName());
        //用户对象
        User user = userService.findUser(dynaInfo.getCreateBy());
        //用户名
        String nickName = dynaInfo.getCreateName();
        String authorName = dynaInfo.getCreateName();
        int isVip = 0;
        long uid = 0;
        if (user != null) {
            nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
            authorName = user.getUsername();
            isVip = user.getVip();
            uid = user.getUid();
        }
        json.put("authorName", authorName);
        json.put("nickname", nickName);
        //用户头像
        json.put("authorPhoto", WebUtils.face(uid, DEFAULT_AUTHORPHOTO_SIZE));
        //贡献油值
        json.put("contribution", dynaInfo.getPetrol());
        //是否有图片(0:没有，1：有）
        json.put("isHasImg", dynaInfo.getIsPic());
        //是否推荐(0:不是，1：是）
        json.put("isRecommend", dynaInfo.getRecommend());
        //是否为精华帖子（1和2：为精华，0：不是精华）
        json.put("isPick", dynaInfo.getPick());
        //帖子ID
        json.put("topicId", dynaInfo.getTopicId());
        //是否认证
        json.put("isVip", isVip);
        //点赞数
        json.put("praiseCount", dynaInfo.getPraiseCount());
        //获取认证用户的品牌图标
		String brandLogo = "";
		if (user != null && user.getVip() == User.IS_VIP) {
			String vipInfo = user.getVipInfo();
			brandLogo = BrandIdUrlMap.getBrandLogo(vipInfo);
		}
		json.put("brandLogo", brandLogo);
        //动态图片数组列表
        JSONArray images = new JSONArray();
        List<DynaImage> dynaImages = dynaInfo.getImages();
        int imgCount = dynaImages.size();
        for (DynaImage dynaImage : dynaImages) {// 获取图片列表信息(URL,width,height必须有值
            if (StringUtils.isBlank(dynaImage.getUrl())) {
                continue;
            }
            /*无宽高，多图时也出; 无宽高单张图时不出*/
            if (imgCount == 1 && dynaImage.getWidth() == 0 && dynaImage.getHeight() == 0) {
                break;
            }
            JSONObject o = new JSONObject();
            o.put("seq", dynaImage.getSeq());
            o.put("url", dynaImage.getUrl500x500());
            o.put("width", dynaImage.getWidth());
            o.put("height", dynaImage.getHeight());
            o.put("qua", imageQua);
            images.add(o);
        }
        json.put("images", images);
        json.put("dynaType", dynaInfo.getType());

        //动态内容
        String content = WebUtils.transformNoBBSFaceThenLimit(dynaInfo.getContent(), STRING_LENGTH_300);
        json.put("content", xssEncode == 0 ? content : EncodeUtils.encodeForHTMLFilterNull(content));

        //根据不同动态类型，返回不同的动态内容
        json = this.setSpecialDynaByType4App(json, dynaInfo, dynaInfo.getType());
        return json;
    }

    /**
     * 组装动态Json
     *
     * @param dynaInfo
     * @param xssEncode
     * @return
     */
    public JSONObject toJson4App2(DynaInfo dynaInfo, int xssEncode) {
        //获取配置文件中的动态切图参数
        int imageQua = systemConfig.getImageQua();

        JSONObject json = new JSONObject();
        json.put("dynaInfoId", dynaInfo.getDynaInfoId());
        //回帖数
        json.put("postCount", dynaInfo.getPostCount());
        //动态发布时间
        json.put("pubTime", dynaInfo.getCreateDate());
        //版块ID
        json.put("forumId", dynaInfo.getForumId());
        json.put("forumName", dynaInfo.getForumName());
        //用户ID
        json.put("createBy", dynaInfo.getCreateBy());
        // 根据UserID获取昵称、头像
        User user = userService.findUser(dynaInfo.getCreateBy());
        String nickName = dynaInfo.getCreateName();
        int isVip = 0;
        long uid = 0;
        String vipInfo = "";
        if (user != null) {
            nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
            isVip = user.getVip();
            uid = dynaInfo.getCreateBy();
            vipInfo = user.getVipInfo();
        }
        json.put("nickName", nickName);
        //是否有图片(0:没有，1：有）
        json.put("isHasImg", dynaInfo.getIsPic());
        //贡献油值
        json.put("petrol", dynaInfo.getPetrol());
        //用户头像
        json.put("authorPhoto", WebUtils.face(uid, DEFAULT_AUTHORPHOTO_SIZE));
        //是否认证
        json.put("isVip", isVip);
        //获取认证会员的品牌小图标
        String brandLogo = "";
        if(isVip == User.IS_VIP) {
        	brandLogo = BrandIdUrlMap.getBrandLogo(vipInfo);
        }
        json.put("brandLogo", brandLogo);
        //点赞数
        json.put("praiseCount", dynaInfo.getPraiseCount());
        json.put("dynaType", dynaInfo.getType());
        //动态图片数组列表
        JSONArray images = new JSONArray();
        List<DynaImage> dynaImages = dynaInfo.getImages();
        int imgCount = dynaImages.size();
        for (DynaImage dynaImage : dynaImages) {// 获取图片列表信息(URL,width,height必须有值
            if (StringUtils.isBlank(dynaImage.getUrl())) {
                continue;
            }
            /*无宽高，多图时也出; 无宽高单张图时不出*/
            if (imgCount == 1 && dynaImage.getWidth() == 0 && dynaImage.getHeight() == 0) {
                break;
            }
            JSONObject o = new JSONObject();
            o.put("seq", dynaImage.getSeq());
            o.put("url", dynaImage.getUrl500x500());
            o.put("width", dynaImage.getWidth());
            o.put("height", dynaImage.getHeight());
            o.put("qua", imageQua);
            images.add(o);
        }
        json.put("images", images);
        //动态内容
        String content = WebUtils.transformNoBBSFaceThenLimit(dynaInfo.getContent(), STRING_LENGTH_300);
        json.put("content", xssEncode == 0 ? content : EncodeUtils.encodeForHTMLFilterNull(content));
        //根据不同动态类型，返回不同的动态内容
        json = this.setSpecialDynaByType4App2(json, dynaInfo, dynaInfo.getType());

        return json;
    }
    
    /**
     * 组装动态Json
     *
     * @param dynaInfo
     * @param xssEncode
     * @return
     */
    public JSONObject toJson4App3(DynaInfo dynaInfo, int xssEncode) {
        //获取配置文件中的动态切图参数
        int imageQua = systemConfig.getImageQua();

        JSONObject json = new JSONObject();
        json.put("dynaInfoId", dynaInfo.getDynaInfoId());
        //回帖数
        json.put("postCount", dynaInfo.getPostCount());
        //动态发布时间
        json.put("pubTime", dynaInfo.getCreateDate());
        //用户ID
        json.put("createBy", dynaInfo.getCreateBy());
        // 根据UserID获取昵称、头像
        User user = userService.findUser(dynaInfo.getCreateBy());
        String nickName = dynaInfo.getCreateName();
        int isVip = 0;
        long uid = 0;
        String vipInfo = "";
        if (user != null) {
            nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
            isVip = user.getVip();
            uid = dynaInfo.getCreateBy();
            vipInfo = user.getVipInfo();
        }
        json.put("nickName", nickName);
        //是否有图片(0:没有，1：有）
        json.put("isHasImg", dynaInfo.getIsPic());
        //贡献油值
        json.put("petrol", dynaInfo.getPetrol());
        //用户头像
        json.put("authorPhoto", WebUtils.face(uid, DEFAULT_AUTHORPHOTO_SIZE));
        //是否认证
        json.put("isVip", isVip);
        //获取认证会员的品牌小图标
        String brandLogo = "";
        if(isVip == User.IS_VIP) {
        	brandLogo = BrandIdUrlMap.getBrandLogo(vipInfo);
        }
        json.put("brandLogo", brandLogo);
        //点赞数
        json.put("praiseCount", dynaInfo.getPraiseCount());
        json.put("dynaType", dynaInfo.getType());
        //动态图片数组列表
        JSONArray images = new JSONArray();
        List<DynaImage> dynaImages = dynaInfo.getImages();
        int imgCount = dynaImages.size();
        for (DynaImage dynaImage : dynaImages) {// 获取图片列表信息(URL,width,height必须有值
            if (StringUtils.isBlank(dynaImage.getUrl())) {
                continue;
            }
            /*无宽高，多图时也出; 无宽高单张图时不出*/
            if (imgCount == 1 && dynaImage.getWidth() == 0 && dynaImage.getHeight() == 0) {
                break;
            }
            JSONObject o = new JSONObject();
            o.put("seq", dynaImage.getSeq());
            o.put("url", dynaImage.getUrl500x500());
            o.put("width", dynaImage.getWidth());
            o.put("height", dynaImage.getHeight());
            o.put("qua", imageQua);
            images.add(o);
        }
        json.put("images", images);
        //动态内容
        String content = WebUtils.transformNoBBSFaceThenLimit(dynaInfo.getContent(), STRING_LENGTH_300);
        json.put("content", xssEncode == 0 ? content : EncodeUtils.encodeForHTMLFilterNull(content));
        //根据不同动态类型，返回不同的动态内容
        json = this.setSpecialDynaByType4App3(json, dynaInfo, dynaInfo.getType());

        return json;
    }

    /**
     * 组装动态Json
     *
     * @param dynaInfo
     * @param sourceAgent
     * @param imageQua
     * @return
     */
    public JSONObject toJson4Pc(DynaInfo dynaInfo, int sourceAgent, int imageQua) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("postCount", dynaInfo.getPostCount());
        jsonObject.put("pubTime", dynaInfo.getCreateDate());
        jsonObject.put("topicTitle", dynaInfo.getTitle() == null ? "" : dynaInfo.getTitle());
        jsonObject.put("forumName", dynaInfo.getForumName() == null ? "" : dynaInfo.getForumName());
        jsonObject.put("isPick", (dynaInfo.getPick() == 1 || dynaInfo.getPick() == 2));
        jsonObject.put("isPost", (dynaInfo.isTopic()));
        jsonObject.put("authorId", dynaInfo.getCreateBy());
        jsonObject.put("forumId", dynaInfo.getForumId());
        String authorName = dynaInfo.getCreateName(), nickName = dynaInfo.getCreateName();
        long uid = 0;
        // 根据UserID获取昵称、头像
        User user = userService.findUser(dynaInfo.getCreateBy());
        if (user != null) {
            authorName = user.getUsername();
            nickName = user.getNickname() == null ? user.getUsername() : user.getNickname();
            uid = dynaInfo.getCreateBy();
        }
        jsonObject.put("authorName", authorName);
        jsonObject.put("nickname", nickName);
        jsonObject.put("authorPhoto", WebUtils.face(uid, DEFAULT_AUTHORPHOTO_SIZE));
        jsonObject.put("contribution", dynaInfo.getPetrol());
        jsonObject.put("topicId", dynaInfo.getTopicId());
        jsonObject.put("isRecommend", (dynaInfo.getRecommend() == 1));
        jsonObject.put("content", WebUtils.transformNoBBSFaceThenLimit(dynaInfo.getContent(), STRING_LENGTH_300, sourceAgent));
        jsonObject.put("dynaInfoId", dynaInfo.getDynaInfoId());
        jsonObject.put("type", dynaInfo.getType());
        JSONArray images = new JSONArray();
        List<DynaImage> dynaImages = dynaInfo.getImages();
        int imgCount = dynaImages.size();
        for (DynaImage dynaImage : dynaImages) {// 获取图片列表信息(URL,width,height必须有值
            if (StringUtils.isBlank(dynaImage.getUrl())) {
                continue;
            }
            /*无宽高，多图时也出; 无宽高单张图时不出*/
            if (imgCount == 1 && dynaImage.getWidth() == 0 && dynaImage.getHeight() == 0) {
                break;
            }
            JSONObject o = new JSONObject();
            o.put("seq", dynaImage.getSeq());
            o.put("url", dynaImage.getUrl500x500());
            o.put("width", dynaImage.getWidth());
            o.put("height", dynaImage.getHeight());
            o.put("qua", imageQua);
            images.add(o);
        }
        jsonObject.put("images", images);
        return jsonObject;
    }

    /**
     * 根据不同动态类型，返回不同的动态列表内容 包括字段:content
     *
     * @param dynaType
     */
    public JSONObject setSpecialDynaByType4App(JSONObject jsonObject, DynaInfo dynaInfo, int dynaType) {
        Club club;
        String clubName, clubUrl;
        String content = dynaInfo.getContent();
        long targetId = dynaInfo.getTargetId();
        String dynaUrl = getDynaUrl(dynaInfo);
        switch (dynaType) {
            //动态类型1-普通帖子（旧数据包含提问帖子）
            case DynaInfo.TYPE_TOPIC:
                break;
            //动态类型2-说说动态
            case DynaInfo.TYPE_COMMENT:
                targetId = dynaInfo.getDynaInfoId();
                break;
            //动态类型3-图片动态
            case DynaInfo.TYPE_PICTURE:
                Album album = albumService.getAlbumById(targetId);//获取相册
                String albumName = album == null ? "" : album.getName();//相册名字
                //组装带有链接的相册提示
                content = "上传了" + dynaInfo.getPictureNum() + "张相片到《" + albumName + "》";
                jsonObject.put("albumName", albumName);
                break;
            //动态类型4-提问帖子
            case DynaInfo.TYPE_QUESTION:
                break;
            //动态类型5-公告动态
            case DynaInfo.TYPE_NOTICE:
                content = "发布了公告：" + content;
                break;
            //动态类型6-活动动态
            case DynaInfo.TYPE_ACTIVITY:
            	if (dynaInfo.getIsOfficialClubDyna()==DynaInfo.IS_OFFICIAL){
            		OActivity oActivity=oActivityService.findValidActivity(targetId);
            		content = oActivity == null ? "" : oActivity.getTitle();//活动标题
                    String picUrl = oActivity == null ? "" : oActivity.getPicUrl();//活动图片
                    jsonObject.put("activityCover", picUrl);
            	}else{
            		Activity activity = activityService.findById(targetId);
                    content = activity == null ? "" : activity.getTitle();//活动标题
                    String picUrl = activity == null ? "" : activity.getPicUrl();//活动图片
                    jsonObject.put("activityCover", picUrl);
            	}
                
                break;
            //动态类型7-新会员加入动态
            case DynaInfo.TYPE_JOIN_CLUB:
                club = clubService.getClub(dynaInfo.getClubId());//获取车友会
                clubName = club == null ? "" : club.getName();
                content = "Hello，我已经加入了" + clubName + "，现在我是一个有组织的人了，欢迎大家来围观！";
                break;
            //动态类型8-创建车友会动态
            case DynaInfo.TYPE_CREATE_CLUB:
                club = clubService.getClub(dynaInfo.getClubId());//获取车友会
                clubName = club == null ? "" : club.getName();
                clubUrl = club == null ? "" : club.getClubUrl();//车友会域名
                String targetUrl = systemConfig.getRoot() + "/" + clubUrl;
                content = "创建了" + clubName + " 车友会主页：" + targetUrl + ", 大家快去邀请车友加入吧！";
                break;
            //获取投票人数
            case DynaInfo.TYPE_VOTE:
                Vote vote = voteService.findVoteByVoteId(targetId);
                long voteCount = vote == null ? 0 : vote.getVoteCount();
                jsonObject.put("voteCount", voteCount);
                break;
            default:
                break;
        }
        jsonObject.put("dynaTargetId", targetId);
        jsonObject.put("content", content);
        jsonObject.put("dynaUrl", dynaUrl );
        return jsonObject;
    }

    /**
     * 获取动态的终端（帖子页，动态终端页，活动终端页）
     *
     * @param dynaInfo
     * @return
     */
    private String getDynaUrl(DynaInfo dynaInfo) {
        if (dynaInfo.getTopicId() > 0) {
            return systemConfig.getBbsRoot() + "/topic-" + dynaInfo.getTopicId() + ".html";
        }
        long clubId = dynaInfo.getClubId();
        Club club = clubService.getValidClub(clubId);

        if (dynaInfo.getType() != DynaInfo.TYPE_ACTIVITY) {
            return systemConfig.getUcRoot() + "/" + dynaInfo.getCreateBy() + "/dt/" + dynaInfo.getDynaInfoId() + "/";
        }
        if (dynaInfo.getType() == DynaInfo.TYPE_ACTIVITY) {
        	if(dynaInfo.getIsOfficialClubDyna()==DynaInfo.IS_OFFICIAL){
        		
        		OActivity oActivity=oActivityService.findValidActivity(dynaInfo.getTargetId());
        		if(oActivity!=null){
        			long oClubId = oActivity.getoClubId();
    				OClub oClub=oClubService.findValidClub(oClubId);
    				if (oClub == null) {
                        return "";
                    }
    				String clubUrl = oClub == null ? "" : oClub.getUrl();//车友会域名
            		return systemConfig.getRoot() + "/brand/" + clubUrl + "/activity/a" + dynaInfo.getTargetId() + "/";
        		}
        	}else{
                if (club == null) {
                    return "";
                }
        		return systemConfig.getRoot() + "/" + club.getClubUrl() + "/activity/a" + dynaInfo.getTargetId() + "/";
        	}
        }
        return "";
    }
    
    /**
     * 根据不同动态类型，返回不同的动态列表内容 包括字段:content
     *
     * @param dynaType
     */
    public JSONObject setSpecialDynaByType4App2(JSONObject jsonObject, DynaInfo dynaInfo, int dynaType) {
        Club club;
        String clubName, clubUrl;
        long clubId = dynaInfo.getClubId();//车友会ID
        String content = dynaInfo.getContent();
        long targetId = dynaInfo.getTargetId();

        switch (dynaType) {
            //动态类型1-普通帖子（旧数据包含提问帖子）
            case DynaInfo.TYPE_TOPIC:
                //帖子Title
                jsonObject.put("topicTitle", dynaInfo.getTitle() == null ? ""
                        : dynaInfo.getTitle());
                //是否推荐(0:不是，1：是）
                jsonObject.put("isRecommend", dynaInfo.getRecommend());
                //是否为精华帖子（1和2：为精华，0：不是精华）
                jsonObject.put("isPick", dynaInfo.getPick());
                //帖子ID
                jsonObject.put("topicId", dynaInfo.getTopicId());
                //版块ID
        		jsonObject.put("forumId", dynaInfo.getForumId());
        		//版块名字
        		String[] filterArray = {"论坛","分会"};
        		jsonObject.put("forumName", StringUtil.filterString(dynaInfo.getForumName(), filterArray));
        		//APP帖子协议
        		jsonObject.put("topicUrl", AppControllerStatic.APP_BBS_TOPIC_URL + dynaInfo.getTopicId());
                break;
            //动态类型2-说说动态
            case DynaInfo.TYPE_COMMENT:
                targetId = dynaInfo.getDynaInfoId();
                break;
            //动态类型3-图片动态
            case DynaInfo.TYPE_PICTURE:
                Album album = albumService.getAlbumById(targetId);//获取相册
                String albumName = album == null ? "" : album.getName();//相册名字
                //组装带有链接的相册提示
                content = "上传了" + dynaInfo.getPictureNum() + "张相片到《" + albumName + "》";
                break;
            //动态类型4-提问帖子
            case DynaInfo.TYPE_QUESTION:
                //帖子Title
                jsonObject.put("topicTitle", dynaInfo.getTitle() == null ? "" : dynaInfo.getTitle());
                //是否推荐(0:不是，1：是）
                jsonObject.put("isRecommend", dynaInfo.getRecommend());
                //是否为精华帖子（1和2：为精华，0：不是精华）
                jsonObject.put("isPick", dynaInfo.getPick());
                //帖子ID
                jsonObject.put("topicId", dynaInfo.getTopicId());
                //版块ID
        		jsonObject.put("forumId", dynaInfo.getForumId());
        		//版块名字
        		String[] filterArrayQ = {"论坛","分会"};
        		jsonObject.put("forumName", StringUtil.filterString(dynaInfo.getForumName(), filterArrayQ));
        		//APP帖子协议
        		jsonObject.put("topicUrl", AppControllerStatic.APP_BBS_TOPIC_URL + dynaInfo.getTopicId());
                break;
            //动态类型5-公告动态
            case DynaInfo.TYPE_NOTICE:
                break;
            //动态类型6-活动动态
            case DynaInfo.TYPE_ACTIVITY:
            	if (dynaInfo.getIsOfficialClubDyna()==DynaInfo.IS_OFFICIAL){
            		OActivity oActivity=oActivityService.findValidActivity(targetId);
                    content = oActivity == null ? "" : oActivity.getTitle();//活动标题
                    String picUrl = oActivity == null ? "" : oActivity.getPicUrl();//活动图片
                    jsonObject.put("activityCover", picUrl);
                    jsonObject.put("activityCost", oActivity == null ? 0 : oActivity.getMoney());
                    jsonObject.put("signUpCount", oActivity == null ? 0 : oActivity.getJoinNum());
            	}else{
            		Activity activity = activityService.findById(targetId);
                    content = activity == null ? "" : activity.getTitle();//活动标题
                    String picUrl = activity == null ? "" : activity.getPicUrl();//活动图片
                    jsonObject.put("activityCover", picUrl);
                    jsonObject.put("activityCost", activity == null ? 0 : activity.getMoney());
                    jsonObject.put("signUpCount", activity == null ? 0 : activity.getJoinNum());
            	}
                break;
            //动态类型7-新会员加入动态
            case DynaInfo.TYPE_JOIN_CLUB:
                club = clubService.getClub(clubId);//获取车友会
                clubName = club == null ? "" : club.getName();
                content = "Hello，我已经加入了" + clubName + "，现在我是一个有组织的人了，欢迎大家来围观！";
                break;
            //动态类型8-创建车友会动态
            case DynaInfo.TYPE_CREATE_CLUB:
                club = clubService.getClub(clubId);//获取车友会
                clubUrl = club == null ? "" : club.getClubUrl();//车友会域名
                clubName = club == null ? "" : club.getName();
                String targetUrl = systemConfig.getRoot() + "/" + clubUrl;
                content = "创建了" + clubName + " 车友会主页：" + targetUrl + ", 大家快去邀请车友加入吧！";
                break;
            //获取投票人数
            case DynaInfo.TYPE_VOTE:
                Vote vote = voteService.findVoteByVoteId(targetId);
                long voteCount = vote == null ? 0 : vote.getVoteCount();
                jsonObject.put("voteCount", voteCount);
                break;
            default:
                break;
        }

        jsonObject.put("dynaTargetId", targetId);
        jsonObject.put("content", content);
        return jsonObject;
    }
    
    /**
     * 根据不同动态类型，返回不同的动态列表内容 包括字段:content
     *
     * @param dynaType
     */
    public JSONObject setSpecialDynaByType4App3(JSONObject jsonObject, DynaInfo dynaInfo, int dynaType) {
    	String content = dynaInfo.getContent();
    	long targetId = dynaInfo.getTargetId();
    	
    	switch (dynaType) {
    	//动态类型1-普通帖子（旧数据包含提问帖子）
    	case DynaInfo.TYPE_TOPIC:
    		//帖子Title
    		jsonObject.put("topicTitle", dynaInfo.getTitle() == null ? "" : dynaInfo.getTitle());
    		//是否推荐(0:不是，1：是）
    		jsonObject.put("isRecommend", dynaInfo.getRecommend());
    		//是否为精华帖子（1和2：为精华，0：不是精华）
    		jsonObject.put("isPick", dynaInfo.getPick());
    		//帖子ID
    		jsonObject.put("topicId", dynaInfo.getTopicId());
    		//版块ID
    		jsonObject.put("forumId", dynaInfo.getForumId());
    		//版块名字
    		String[] filterArray = {"论坛","分会"};
    		jsonObject.put("forumName", StringUtil.filterString(dynaInfo.getForumName(), filterArray));
    		//APP帖子协议
    		jsonObject.put("topicUrl", AppControllerStatic.APP_BBS_TOPIC_URL + dynaInfo.getTopicId());
    		break;
    	//动态类型2-说说动态
    	case DynaInfo.TYPE_COMMENT:
    		targetId = dynaInfo.getDynaInfoId();
    		long clubId = dynaInfo.getClubId();//车友会ID
    		Club club = clubService.getClub(clubId);//获取车友会
    		if(club != null) {
                String clubName =  club.getName();
                jsonObject.put("clubName", clubName);
                jsonObject.put("clubId", clubId);
    		}
            
    		break;
    	//动态类型4-提问帖子
    	case DynaInfo.TYPE_QUESTION:
    		//帖子Title
    		jsonObject.put("topicTitle", dynaInfo.getTitle() == null ? "" : dynaInfo.getTitle());
    		//是否推荐(0:不是，1：是）
    		jsonObject.put("isRecommend", dynaInfo.getRecommend());
    		//是否为精华帖子（1和2：为精华，0：不是精华）
    		jsonObject.put("isPick", dynaInfo.getPick());
    		//帖子ID
    		jsonObject.put("topicId", dynaInfo.getTopicId());
    		//版块ID
    		jsonObject.put("forumId", dynaInfo.getForumId());
    		//版块名字
    		String[] filterArrayQ = {"论坛","分会"};
    		jsonObject.put("forumName", StringUtil.filterString(dynaInfo.getForumName(), filterArrayQ));
    		//APP帖子协议
    		jsonObject.put("topicUrl", AppControllerStatic.APP_BBS_TOPIC_URL + dynaInfo.getTopicId());
    		break;
    	default:
    		break;
    	}
    	
    	jsonObject.put("dynaTargetId", targetId);
    	jsonObject.put("content", content);
    	return jsonObject;
    }
}
